<?php

namespace App\Http\Controllers\Api;

use App\Classify;
use App\Comment;
use App\CommentLike;
use App\DemandAllureLabel;
use App\DemandBrowseRecord;
use App\DemandImg;
use App\Demands;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Industries;
use App\News;
use App\NewsBrowseRecord;
use App\NewsLabel;
use App\NewsLike;
use App\NewsXDemand;
use App\User;
use App\UserAttentionActivity;
use App\UserAttentionDemand;
use App\UserAttentionNews;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class NewsController extends Controller
{
    //资讯
    public function getNewsList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
//        if(!$user)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page   =!is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit  =!is_null($request->get('limit')) ? $request->get('limit') : 10;

        $province       = !is_null($request->get('province'))   ? $request->get('province')     : '';
        $city           = !is_null($request->get('city'))       ? $request->get('city')         : '';
        $industry_id    = !is_null($request->get('industry_id'))? $request->get('industry_id')  : 0;
        $classify_id    = !is_null($request->get('classify_id'))? $request->get('classify_id')  : 0;
        $is_hot         = !is_null($request->get('is_hot'))      ? $request->get('is_hot')      : 0;


        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;
        $news   = News::whereStatus(1);
        if ($province)
            $news=$news->whereProvince($province);
        if ($city)
            $news=$news->whereCity($city);
        if ($classify_id)
            $news=$news->whereClassifyId($classify_id);
        if ($industry_id)
            $news=$news->whereIndustryId($industry_id);

        if ($is_hot==1)
            $news=$news->orderBy('browse_num','desc')->orderBy('attention_num','desc');
        else
            $news=$news->orderBy('sort','asc')->orderBy('updated_at','desc');

        $page_info['total']=$news->count();
        $news=$news->offset($page * $limit)->limit($limit)
                ->get(['id','title','img_id','desc','type','video_id','advert_img_id','created_at','updated_at']);

        if (count($news) > 0){
            /** @var News $item */
            foreach ($news as $item){
                $comments=Comment::whereNewsId($item->id)->whereType('news')->whereStatus(1)
                    ->orderBy('created_at','desc')->orderBy('is_official','desc')->offset(0)->limit(5)->get();
                if (count($comments) > 0){
                    foreach ($comments as $comment){
                        $user_info=CommonManager::getUserBasicInfo($comment->user_id);
                        if ($user_info)
                            $comment->user_info=$user_info;
                        else
                            $comment->user_info=[];
                    }
                }
                $item->img_url          =FileManager::getImgUrl($item->img_id);
                $item->advert_img_url   =FileManager::getImgUrl($item->advert_img_id);
                $item->video_url        =FileManager::getVideoUrl($item->video_id);
                $item->lable_array      =NewsLabel::whereNewsId($item->id)->pluck('name')->toArray();
                $item->is_collection    = $user ? (UserAttentionNews::whereUserId($user->id)->whereNewsId($item->id)->first() ? 1 :2 ) : 2;
                $item->comments         =$comments;
            }
        }
        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$news]);
    }

    public function getNewsDetail(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
//        if(!$user)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $user_id=0;
        $id=$request->get('id');
        if ($user)
            $user_id=$user->id;

        $newsIsDelete = News::whereId($id)->withTrashed()->first();
        if($newsIsDelete && $newsIsDelete->deleted_at!=null){
            if($user){
                $userAttackActivity = UserAttentionNews::whereNewsId($newsIsDelete->id)->whereUserId($user->id)->first();
                if($userAttackActivity){
                    return response()->json(['level'=>'error','message'=>'该资讯已被删除','data' => 1]);
                }else{
                    return response()->json(['level'=>'error','message'=>'该资讯已被删除','data' => 2]);
                }
            }else{
                return response()->json(['level'=>'error','message'=>'该活动已被删除','data' => '']);
            }
        }

        $news=News::whereId($id)->whereStatus(1)->first();
        if ($news){
            //浏览数+1
//            $news->browse_num=$news->browse_num+1;
//            $news->save();
            //TODO 记录浏览来源
            self::addReadNewsRecord($id,$user_id,$request->ip());

            $link_demand_ids    = NewsXDemand::whereNewsId($news->id)->pluck('demand_id')->toArray();
            $link_demand        = Demands::whereIn('id',$link_demand_ids)->get();
            if (count($link_demand) > 0){
                /** @var Demands $demand */
                foreach ($link_demand as $demand){
                    $url_array=[];
                    $classify   =Classify::whereId($demand->classify_id)    ->first();
                    $industry   =Industries::whereId($demand->industry_id)  ->first();
                    $imgs       =DemandImg::whereDemandId($demand->id)      ->get();
                    $label      =DemandAllureLabel::whereDemandId($demand->id)->pluck('name')->toArray();

                    if (count($imgs) > 0){
                        /** @var DemandImg $img */
                        foreach ($imgs as $img){
                            $url=FileManager::getImgUrl($img->img_id);
                            array_push($url_array,$url);
                        }
                    }
                    $demand->classify_name  = $classify ? $classify->name :'其他';
                    $demand->industry_name  = $industry ? $industry->name :'其他';
                    $demand->img_array_url  = $url_array;
                    $demand->label_arr      = $label;
                    $demand->is_collection  = $user ? (UserAttentionDemand::whereUserId($user->id)->whereDemandId($demand->id)->first() ? 1 :2 ) : 2;

                }
            }

            $news->img_url          =FileManager::getImgUrl($news->img_id);
            $news->advert_img_url   =FileManager::getImgUrl($news->advert_img_id);
            $news->video_url        =FileManager::getVideoUrl($news->video_id);
            $news->lable_array      = NewsLabel::whereNewsId($id)->pluck('name')->toArray();
            $news->is_collection    = $user ? (UserAttentionNews::whereUserId($user->id)->whereNewsId($id)->first() ? 1 :2 ) : 2;
            $news->link_demands     = $link_demand;
            $news->is_like = 0;
            if ($user_id){
                $isLike = NewsLike::whereNewsId($news->id)->whereUserId($user_id)->first();
                if($isLike){
                    $news->is_like = 1;
                }
            }


            return response()->json(['level'=>'success','message'=>'获取成功','data'=>$news]);
        } else
        {
            return response()->json(['level'=>'error','message'=>'资讯不存在','data'=>[]]);
        }
    }
    protected static function addReadNewsRecord($news_id,$user_id=0,$ip=null){
//        新增记录
        if (!$user_id)
            return 0;
        $news=News::whereId($news_id)->whereStatus(1)->first();
        $news_record=NewsBrowseRecord::whereNewsId($news_id)->whereUserId($user_id)->orderBy('created_at','desc')->first();
        if ($news_record){
            if (strtotime($news_record->created_at) + 300 <= time() ){
                $newRecord=new NewsBrowseRecord();
                if ($user_id)
                    $newRecord->user_id=$user_id;
                if ($ip)
                    $newRecord->ip=$ip;
                $newRecord->news_id=$news_id;
                $newRecord->save();
                if ($news){
                    $news->browse_num=$news->browse_num+1;
                    $news->save();
                }
            }
        } else {
            $newRecord=new NewsBrowseRecord();
            if ($user_id)
                $newRecord->user_id=$user_id;
            if ($ip)
                $newRecord->ip=$ip;
            $newRecord->news_id=$news_id;
            $newRecord->save();
            if ($news){
                $news->browse_num=$news->browse_num+1;
                $news->save();
            }
        }
        return 1;

    }

    /**
     * 资讯评论接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function releaseNewsComment(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $newsId         = !is_null($request->get('news_id')) ? $request->get('news_id') : 0;
        $content        = !is_null($request->get('content')) ? $request->get('content') : '';
        $toCommentId    = !is_null($request->get('comment_id')) ? $request->get('comment_id') : 0;
        $toUserId       = !is_null($request->get('user_id')) ? $request->get('user_id') : 0;
        $type           = !is_null($request->get('type')) && $request->get('type') != '' ? $request->get('type') : 'default';
        $commentType    = !is_null($request->get('comment_type')) && $request->get('comment_type') != '' ? $request->get('comment_type') : 'default';
        $demandId       = !is_null($request->get('demand_id')) ? $request->get('demand_id') : 0;

        if($type == 'default'){
            $news = News::whereId($newsId)->whereStatus(1)->first();
            if(!$news)
                return response()->json(['level' => 'error','message' => '资讯不存在']);

            if($content == '')
                return response()->json(['level' => 'error','message' => '请填写评论内容']);

            $newComment = new Comment();
            $newComment->user_id         = $user->id;
            $newComment->content         = $content;
            $newComment->news_id         = $news->id;
            if($commentType == 'reply'){
                $newComment->to_comment_id = $toCommentId;
                $newComment->to_user_id    = $toUserId;
            }
            $newComment->type            = 'news';
            $newComment->ip              = $request->ip();
            $newComment->status          = 0;
            $newComment->save();
        }elseif($type == 'demand'){
            $demand = Demands::whereId($demandId)->whereIsShop(1)->whereReview(1)->first();
            if(!$demand)
                return response()->json(['level' => 'error','message' => '服务不存在']);

            if($content == '')
                return response()->json(['level' => 'error','message' => '请填写评论内容']);

            $newComment = new Comment();
            $newComment->user_id         = $user->id;
            $newComment->content         = $content;
            $newComment->demand_id       = $demand->id;
            if($commentType == 'reply'){
                $newComment->to_comment_id = $toCommentId;
                $newComment->to_user_id    = $toUserId;
            }
            $newComment->type            = 'demand';
            $newComment->ip              = $request->ip();
            $newComment->status          = 0;
            $newComment->save();
        }else{
            return response()->json(['level' => 'error','message' => '系统错误']);
        }


        return response()->json(['level' => 'success','message' => '已提交审核','data' => $newComment]);
    }

    public function getNewsComment(Request $request){
        $user = UserManager::isLogin($request);

        $news_id    = $request->get('news_id');
        $demandId   = $request->get('demand_id');
        $type       = !is_null($request->get('type')) && $request->get('type') != '' ? $request->get('type') : 'default';

        $userId = 0;
        if($user){
            $userId = $user->id;
        }

        $page   =!is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit  =!is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;
        if($type == 'default'){
            $page_info['total']=Comment::whereNewsId($news_id)->whereToCommentId(0)->whereStatus(1)->count();
            $comments=CommonManager::getCommentList($news_id,'news',$limit,$page,$userId);
        }elseif($type == 'demand'){
            $page_info['total']=Comment::whereDemandId($demandId)->whereToCommentId(0)->whereStatus(1)->count();
            $comments=CommonManager::getCommentList($demandId,'demand',$limit,$page,$userId);
        }else{
            $comments = [];
        }

        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$comments]);
    }

    /**
     * 评论点赞接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function commentLikeAction(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $commentId = !is_null($request->get('comment_id')) ? $request->get('comment_id') : 0;

        $comment = Comment::whereId($commentId)->whereStatus(1)->first();
        if(!$comment)
            return response()->json(['level' => 'error','message' => '评论不存在']);

        $thisCommentLike = CommentLike::whereUserId($user->id)->whereCommentId($comment->id)->first();
        if($thisCommentLike){
            $thisCommentLike->forceDelete();

            return response()->json(['level' => 'error','message' => '取消成功']);
        }

        $newCommentLike = new CommentLike();
        $newCommentLike->user_id          = $user->id;
        $newCommentLike->comment_id       = $comment->id;
        $newCommentLike->save();

        return response()->json(['level' => 'success','message' => '点赞成功','data' => $newCommentLike]);
    }

    public function favoriteNews(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $news_id  = !is_null($request->get('news_id')) ? $request->get('news_id') : 0;
        $news = News::whereId($news_id)->whereStatus(1)->first();
        if(!$news)
            return response()->json(['level' => 'error','message' => '资讯不存在']);
        $is_favorite = UserAttentionNews::whereNewsId($news_id)->whereUserId($user->id)->first();
        if ($is_favorite)
            return response()->json(['level'=>'success','message'=>'你已经关注过了','data'=>'is_favorite']);
        $attention = new UserAttentionNews();
        $attention->user_id         = $user->id;
        $attention->news_id         = $news->id;
        $attention->save();

        $news->attention_num += 1;
        $news->save();
        return response()->json(['level'=>'success','message'=>'关注成功','data'=>'is_favorite']);
    }
    public function unFavoriteNews(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $news_id  = !is_null($request->get('news_id')) ? $request->get('news_id') : 0;
//        $news = News::whereId($news_id)->whereStatus(1)->first();
        $is_favorite = UserAttentionNews::whereNewsId($news_id)->whereUserId($user->id)->first();
        if (!$is_favorite)
            return response()->json(['level'=>'success','message'=>'你还没有收藏','data'=>'not_favorite']);
        $is_favorite->delete();

        $news=DB::table('news')->whereId($news_id)->first();
        if($news){
            $attention_num=UserAttentionNews::whereNewsId($news_id)->count();
            DB::table('news')->where('id',$news_id)->update(['attention_num' => $attention_num]);
        }

        return response()->json(['level'=>'success','message'=>'取消关注成功','data'=>'not_favorite']);
    }
    public function likeNews(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $news_id  = !is_null($request->get('news_id')) ? $request->get('news_id') : 0;
        $news = News::whereId($news_id)->whereStatus(1)->first();
        if(!$news)
            return response()->json(['level' => 'error','message' => '点赞失败，资讯不存在']);
        $news_like = NewsLike::whereNewsId($news_id)->whereUserId($user->id)->first();
        if ($news_like){
            $news_like->delete();

            $news->like_num -= 1;
            $news->save();
            return response()->json(['level' => 'error','message' => '取消成功']);
        }

        $new_news_like= new NewsLike();
        $new_news_like->user_id=$user->id;
        $new_news_like->news_id=$news_id;
        $new_news_like->save();

        $news->like_num  += 1;
        $news->save();
        return response()->json(['level' => 'success','message' => '点赞成功']);
    }
}
